// gcc -g libbacktrace.c -o libbacktrace -lbacktrace
#include <backtrace.h>
#include <stdio.h>
#include <stdlib.h>
int num = 0;
// 错误回调函数：在回溯过程中出错时被调用
void error_callback(void *data, const char *msg, int errnum) {
    fprintf(stderr, "Error: %s (%d)\n", msg, errnum);
}

// 栈帧回调函数：获取每一层的函数名、文件名和行号
int full_callback(void *data, uintptr_t pc, const char *filename, int lineno, const char *function) {
    if (filename && function) {
        printf("[#%d] %s:%d, in %s\n", num, filename, lineno, function);
    } else {
        printf("[#%d] %p (no symbol info)\n", num, (void*)pc);
    }
    num++;
    return 0;
}

void print_backtrace() {
    // 创建回溯状态
    struct backtrace_state *state = backtrace_create_state(NULL, 0, error_callback, NULL);
    // 获取调用栈并打印
    backtrace_full(state, 0, full_callback, error_callback, NULL);
}

void func2() {
    print_backtrace();
}

void func1() {
    func2();
}

int main() {
    func1();
    return 0;
}
